package com.sc.nft.admin.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.meta.component.base.api.BaseCommonPage;
import com.meta.component.base.api.CommonResult;
import com.meta.user.client.api.UserLogOffRecordClient;
import com.meta.user.client.res.UserLogOffRecordRes;
import com.sc.nft.admin.request.*;
import com.sc.nft.admin.service.QywxService;
import com.sc.nft.admin.vo.EnumObjVO;
import com.sc.nft.annotation.SysMemberLogin;
import com.sc.nft.dao.*;
import com.sc.nft.dto.UserEcologyHatchRecordsDao;
import com.sc.nft.entity.DaoEcologyPoints;
import com.sc.nft.entity.UserCreatorInfo;
import com.sc.nft.entity.UserEcologyHatchRecords;
import com.sc.nft.entity.UserInfo;
import com.sc.nft.entity.dto.UserResetBankInfoDTO;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.helper.MessageQueueHelper;
import com.sc.nft.helper.SandAccountHelper;
import com.sc.nft.service.*;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import com.sc.nft.util.WeChatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/user")
@Api(tags = "后台用户模块")
public class UserInfoAdminController {

    private final UserCollectionService userCollectionService;

    private final UserInfoService userInfoService;
    private final UserInfoDao userInfoDao;

    private final SandAccountHelper sandAccountHelper;
    private final CheckParameterService checkParameterService;
    private final MerchantPledgeTaskCycleConfDao merchantPledgeTaskCycleConfDao;
    private final UserMerchantPledgeTaskRecordsDao userMerchantPledgeTaskRecordsDao;
    private final UserCollectionDao userCollectionDao;
    private final EcologySmeltingService ecologySmeltingService;
    private final UserEcologyHatchRecordsDao userEcologyHatchRecordsDao;
    private final MessageQueueHelper messageQueueHelper;
    private final UserCreatorInfoDao userCreatorInfoDao;
    private final EcologyHatchShareProfitDao ecologyHatchShareProfitDao;
    private final QywxService qywxService;
    private final UserLogOffRecordClient userLogOffRecordClient;
    private final Redisson redisson;
    private final UserPredictEcologyHatchRewardsRecordsService userPredictEcologyHatchRewardsRecordsService;


    @PostMapping(value = "/transferPage", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户转增列表", notes = "用户转增列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<TransferVO> transferPage(@Valid @RequestBody TransferRequest request) {
        return PageResult.success(userCollectionService.transferLog(request.getFromUserAddress(), request.getToUserAddress(), request.getTransactionHash(), request.getChainUrl(), request.getPageNo(), request.getPageSize()));
    }

    @PostMapping(value = "/userCollectionPage", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户拥有的藏品", notes = "用户拥有的藏品", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<UserCollectionVO> userCollectionPage(@Valid @RequestBody UserCollectionRequest request) {
        Page<UserCollectionVO> userCollectionVOPage = userCollectionService.userCollection(request.getFirstTitle(), request.getPageNo(), request.getPageSize(), request.getStartTime(), request.getEndTime(), request.getUserTel());
        userCollectionVOPage.getRecords().forEach(userCollectionVO -> {
            userCollectionVO.setTypeName(userCollectionVO.getType().getDescription());
        });
        return PageResult.success(userCollectionVOPage);
    }

    @SneakyThrows
    @PostMapping(value = "/userCollectionExcel", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户拥有的藏品导出excel", notes = "用户拥有的藏品导出excel", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public void userCollectionExcel(@Valid @RequestBody UserCollectionRequest request, HttpServletResponse response) {
        List<UserCollectionExcelVO> data = userCollectionService.userCollectionExcel(request.getFirstTitle(), request.getStartTime(), request.getEndTime(), request.getUserTel());
        data.forEach(userCollectionExcelVO -> {
            userCollectionExcelVO.setTypeName(ReceivedCollectionType.getName(userCollectionExcelVO.getType()).getDescription());
            userCollectionExcelVO.setStatusText(userCollectionExcelVO.getStatus());
            userCollectionExcelVO.setOnConsignText(userCollectionExcelVO.getOnConsign());
            userCollectionExcelVO.setFreezingStatusText(userCollectionExcelVO.getFreezingStatus());
        });
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("用户藏品", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserCollectionExcelVO.class).sheet("用户藏品").doWrite(data);
    }

    @PostMapping(value = "/getAdminCollectionChainRecord", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "藏品流转记录", notes = "藏品流转记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<TransferVO> getAdminCollectionChainRecord(@Valid @RequestBody AdminCollectionChainRecordRequest request) {
        return PageResult.success(userCollectionService.getAdminCollectionChainRecord(request.getFirstTitle(), request.getFromUserAddress(), request.getToUserAddress(), request.getTransactionHash(), request.getCollectionType(), request.getStatus(), request.getStartTime(), request.getEndTime(), request.getPageNo(), request.getPageSize()));
    }

    @PostMapping(value = "/getReceivedCollectionType", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取操作类型", notes = "获取操作类型", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result getTypeAndStatusEnum() {
        ReceivedCollectionType[] values = ReceivedCollectionType.values();
        List<EnumObjVO> receivedCollectionList = new ArrayList();

        EnumObjVO enumObjVO = new EnumObjVO();
        enumObjVO.setCode(0);
        enumObjVO.setName("全部");
        receivedCollectionList.add(enumObjVO);
        for (ReceivedCollectionType value : values) {
            EnumObjVO enumVO = new EnumObjVO();
            enumVO.setCode(value.getCode());
            enumVO.setName(value.getDescription());
            receivedCollectionList.add(enumVO);
        }
        List<EnumObjVO> userChainLogStatusEnumsList = new ArrayList();
        UserChainLogStatusEnum[] userChainLogStatusEnums = UserChainLogStatusEnum.values();
        userChainLogStatusEnumsList.add(enumObjVO);

        for (UserChainLogStatusEnum userChainLogStatusEnum : userChainLogStatusEnums) {
            EnumObjVO userChainLogEnumObjVO = new EnumObjVO();
            userChainLogEnumObjVO.setCode(userChainLogStatusEnum.getCode());
            userChainLogEnumObjVO.setName(userChainLogStatusEnum.getDescription());
            userChainLogStatusEnumsList.add(userChainLogEnumObjVO);
        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("collectionType", receivedCollectionList);
        map.put("status", userChainLogStatusEnumsList);

        return Result.success(map);
    }

    @PostMapping(value = "/initUserChain", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "重置溯源链", notes = "重置溯源链", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result initUserChain() {
        userInfoService.initUserChain();
        return Result.success();
    }


    @PostMapping(value = "/restoreAccount", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "还原开户信息", notes = "还原开户信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result restoreAccount(@Valid @RequestBody RestoreAccountRequest request) {
        UserInfo userInfo = userInfoDao.getById(request.getId());
        if (ObjectUtil.isNull(userInfo)) {
            return Result.fail("未找到用户");
        }
        if (BooleanUtil.isFalse(userInfo.getIsSm())) {
            return Result.fail("用户实名未完成");
        }
        if (BooleanUtil.isFalse(userInfo.getSandPayPwd())) {
            return Result.fail("用户为完成衫德开户");
        }

        if (request.getReSm()) {
            userInfo.setIsSm(false);
        }

        if (request.getReSand()) {
            userInfo.setSandAccountOpen(false);
            userInfo.setSandFaceVerify(false);
            userInfo.setSandPayPwd(false);
            userInfo.setSandMasterAccount(null);
        }
        userInfoService.restoreAccount(userInfo);
        return Result.success();
    }

    @PostMapping(value = "/selectResetOutSideKey", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "重置杉德绑卡id前置查询", notes = "重置杉德绑卡id前置查询", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result<SelectResetOutSideKeyVO> selectResetOutSideKey(@Valid @RequestBody DaoUserTelRequest request) {
        return Result.success(userInfoService.selectResetOutSideKey(request.getUserTel()));
    }


    @PostMapping(value = "/resetOutSideKey", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "重置杉德绑卡id", notes = "重置杉德绑卡id", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result resetOutSideKey(@Valid @RequestBody DaoUserTelRequest request) {
        userInfoService.resetOutSideKey(request.getUserTel());
        return Result.success();
    }

//    @PostMapping(value = "/userRelevanceTransfer", produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiOperation(value = "用户关系转移", notes = "用户关系转移", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    @SysMemberLogin
//    @Transactional(rollbackFor = Exception.class)
//    public Result userRelevanceTransfer(@RequestBody UserRelevanceTransferDTO userRelevanceTransferDTO) {
//        // 迁移目标
//        String userTel = userRelevanceTransferDTO.getUserTel();
//        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
//        userInfoQueryWrapper.eq("user_tel", userTel);
//        UserInfo model = (UserInfo) new UserInfo().selectOne(userInfoQueryWrapper);
//        if (model.getId().equals(1L)) {
//            return Result.fail("禁止迁移账户");
//        }
//        // 迁移目标的id
//        Long id = model.getId();
//        // 迁移账号
//        List<String> list = userRelevanceTransferDTO.getList();
//        // 批量处理迁移账号
//        // 迁移逻辑: 把上级id修改,溯源掉所有的上级 ,把所有的当前的上级全部删掉后在写入
//        list.forEach(s -> {
//            // 获取迁移用户
//            QueryWrapper<UserInfo> userInfoQuerySaveWrapper = new QueryWrapper<>();
//            userInfoQuerySaveWrapper.eq("user_tel", s);
//            UserInfo saveUserInfo = (UserInfo) new UserInfo().selectOne(userInfoQuerySaveWrapper);
//            // 原始邀请人,需要获取原始邀请人数据.来减去他对应的邀请人数据
//            Long recommendUserId = saveUserInfo.getRecommendUserId();
//            if (model.getRecommendUserId().equals(saveUserInfo.getId())) {
//                throw new GlobalRunTimeException("迁移目标存在冲突.迁移已中断,之前迁移数据已经迁移完成,冲突用户:" + s);
//            }
//
//            // 已经在其组下了
////            if (recommendUserId.equals(model.getId())) {
////                return;
////            }
//            QueryWrapper<UserInfo> queryWrapperRecommendUserId = new QueryWrapper<>();
//            queryWrapperRecommendUserId.eq("id", recommendUserId);
//            UserInfo userInfoRecommend = (UserInfo) new UserInfo().selectOne(queryWrapperRecommendUserId);
//            userInfoRecommend.setInviteNum(userInfoRecommend.getInviteNum() - 1);
//            if (saveUserInfo.getIsSm()) {
//                userInfoRecommend.setValidInviteNum(userInfoRecommend.getValidInviteNum() - 1);
//            }
//            userInfoRecommend.updateById();
//
//            // 写入迁移用户新的上级id
//            saveUserInfo.setRecommendUserId(id);
//            // 修改目标用户的邀请id
//            saveUserInfo.updateById();
//            // 删除掉用户的上级关系
//            QueryWrapper<UserRelevance> userRelevanceQueryWrapper = new QueryWrapper<>();
//            userRelevanceQueryWrapper.eq("relevance_id", saveUserInfo.getId());
//            new UserRelevance().delete(userRelevanceQueryWrapper);
//
//            // 重新溯源用户上级,把数据写入数据库.让后把溯源链组装好
//            List<Long> arrayList = new ArrayList<>();
//            traceToTheSource(model.getId(), 1, arrayList, saveUserInfo.getId());
//            // 翻转集合
//            Collections.reverse(arrayList);
//            // 组装溯源链
//            String chain = "";
//            for (Long aLong : arrayList) {
//                chain = StrUtil.format("{}{},", chain, aLong);
//            }
//            UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
//            updateWrapper.eq("id", saveUserInfo.getId());
//            updateWrapper.set("recommend_user_id_list", chain.substring(0, chain.length() - 1));
//            new UserInfo().update(updateWrapper);
//            // 查看当前迁入用户是否实名制
//            if (saveUserInfo.getIsSm()) {
//                model.setValidInviteNum(model.getValidInviteNum() + 1);
//            }
//            // 迁入目标的邀请人数+1
//            model.setInviteNum(model.getInviteNum() + 1);
//            model.updateById();
//            // 处理迁移用户的下级关联关系,需要先判定,集合长度是否超过50.
//            QueryWrapper<UserRelevance> relationRelevanceQueryWrapper = new QueryWrapper<>();
//            relationRelevanceQueryWrapper.eq("user_id", saveUserInfo.getId());
//            List<UserRelevance> listUserInfoRelevance = (List<UserRelevance>) new UserRelevance().selectList(relationRelevanceQueryWrapper);
//            if (listUserInfoRelevance.size() > 1000) {
//                throw new GlobalRunTimeException("迁移数据过于庞大");
//            }
//            new UserRelevance().delete(relationRelevanceQueryWrapper);
//            dataBaseSaveRecursion(saveUserInfo.getId(), 1, saveUserInfo.getId());
//
//            // 处理迁移用户的下级关联关系,需要先判定,集合长度是否超过50.
//            QueryWrapper<UserRelevance> migrationRelationRelevanceQueryWrapper = new QueryWrapper<>();
//            migrationRelationRelevanceQueryWrapper.eq("user_id", model.getId());
//            List<UserRelevance> migrationListUserInfoRelevance = (List<UserRelevance>) new UserRelevance().selectList(relationRelevanceQueryWrapper);
//            if (migrationListUserInfoRelevance.size() > 1000) {
//                throw new GlobalRunTimeException("迁移数据过于庞大");
//            }
//            new UserRelevance().delete(migrationRelationRelevanceQueryWrapper);
//            dataBaseSaveRecursion(model.getId(), 1, model.getId());
//        });
//        return Result.success();
//    }
//
//    public void traceToTheSource(Long useUserId, Integer lv, List<Long> chain, Long userId) {
//        // 根据目标用户的id获取目标用户
//        QueryWrapper<UserInfo> userInfoQuerySaveWrapper = new QueryWrapper<>();
//        userInfoQuerySaveWrapper.eq("id", useUserId);
//        UserInfo saveUserInfo = (UserInfo) new UserInfo().selectOne(userInfoQuerySaveWrapper);
//        if (BeanUtil.isEmpty(saveUserInfo)) {
//            return;
//        }
//        UserRelevance userRelevance = new UserRelevance();
//        userRelevance.setUserId(saveUserInfo.getId());
//        userRelevance.setRelevanceId(userId);
//        userRelevance.setLv(lv);
//        userRelevance.setCreateTime(new Date());
//        userRelevance.setUpdateTime(new Date());
//        userRelevance.insert();
//        // 组装溯源链
//        chain.add(saveUserInfo.getId());
//        if (saveUserInfo.getRecommendUserId() != null && !saveUserInfo.getRecommendUserId().equals(0L)) {
//            traceToTheSource(saveUserInfo.getRecommendUserId(), lv + 1, chain, userId);
//        }
//    }
//
//    public void dataBaseSaveRecursion(Long userId, Integer lv, Long originalId) {
//        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper();
//        queryWrapper.eq("recommend_user_id", userId);
//        queryWrapper.select("id");
//        List<UserInfo> list = (List<UserInfo>) new UserInfo().selectList(queryWrapper);
//        dataBaseSave(list, originalId, lv);
//        for (UserInfo info : list) {
//            if (BeanUtil.isNotEmpty(info)) {
//                dataBaseSaveRecursion(info.getId(), lv + 1, originalId);
//            }
//        }
//    }
//
//    public void dataBaseSave(List<UserInfo> list, Long userId, Integer lv) {
//        List<List<UserInfo>> parts = Lists.partition(list, 1000);
//        for (List<UserInfo> part : parts) {
//            List<UserRelevance> userRelevances = new ArrayList<>();
//            for (UserInfo userInfo : part) {
//                UserRelevance userRelevance = new UserRelevance();
//                userRelevance.setUserId(userId);
//                userRelevance.setRelevanceId(userInfo.getId());
//                userRelevance.setLv(lv);
//                userRelevance.setCreateTime(new Date());
//                userRelevance.setUpdateTime(new Date());
//                userRelevances.add(userRelevance);
//            }
//            userRelevanceDao.saveBatch(userRelevances);
//        }
//    }


    @PostMapping(value = "/userResetBankInfo", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户重置银行卡绑定信息", notes = "用户重置银行卡绑定信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result userResetBankInfo(@RequestBody UserResetBankInfoDTO userResetBankInfoDTO) {
        // 是否开启短信验证功能
        if (userResetBankInfoDTO.getIsOpenSms()) {
            checkParameterService.CheckVerificationcode(userResetBankInfoDTO.getUserTel(),
                    userResetBankInfoDTO.getSmsId(),
                    userResetBankInfoDTO.getCodes(),
                    SendSMSEnum.OPERATING_BALANCE.getCode());
        }
        userInfoService.userResetBankInfo(userResetBankInfoDTO);
        return Result.success();
    }


    @PostMapping(value = "/logoutUserRecordsPage", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "注销列表", notes = "注销列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<AdminLogoutUserPageVO> logoutUserPage(@Valid @RequestBody UserTelPageRequest request) {
        BaseCommonPage<UserLogOffRecordRes> result = userLogOffRecordClient.findLogOffUser(request.getUserTel(), request.getPageNo(), request.getPageSize());
        Page<AdminLogoutUserPageVO> object = new Page<>(result.getPageNum(), result.getPageSize(), result.getTotal());
        if (!CollectionUtils.isEmpty(result.getList())) {
            object.setRecords(result.getList().stream().map(item -> {
                AdminLogoutUserPageVO vo = new AdminLogoutUserPageVO();
                vo.setUserId(item.getUserId());
                vo.setUserTel(item.getLogOffKey());
                vo.setCreateTime(item.getCreateTime());
                vo.setReleaseTime(item.getReleaseTime());
                return vo;
            }).collect(Collectors.toList()));
        }
        return PageResult.success(object);
    }

    @PostMapping(value = "/delLogoutUserRecords", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除注销记录", notes = "删除注销记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result delLogoutUserRecords(@Valid @RequestBody IdRequest request) {
//        userInfoService.delLogoutUserRecords(request.getId());
        CommonResult<Boolean> result = userLogOffRecordClient.deleteByUserId(request.getId());
        Assert.isTrue(BooleanUtil.isTrue(result.getData()), () -> new GlobalRunTimeException("该用户不存在注销记录"));

        return PageResult.success();
    }

    @PostMapping(value = "/quotaIncome_mq", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "熔炼冻结金额MQ重新处理", notes = "删除注销记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result quotaIncome_mq(@Valid @RequestBody IdRequest request) {
        UserEcologyHatchRecords userEcologyHatchRecords = userEcologyHatchRecordsDao.getById(request.getId());
        log.info("用户记录重新释放:{}", userEcologyHatchRecords);
        messageQueueHelper.sendMessage(MessageTopic.ECOLOGY_HATCH_TOPIC, userEcologyHatchRecords.getUserId());
//        ecologySmeltingService.quotaIncome(userEcologyHatchRecords.getUserId());
        return PageResult.success();
    }

    @PostMapping(value = "/quotaIncome_local", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "熔炼冻结金额本机重新处理", notes = "删除注销记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result quotaIncome_local(@Valid @RequestBody IdRequest request) {
        UserEcologyHatchRecords userEcologyHatchRecords = userEcologyHatchRecordsDao.getById(request.getId());
        ecologySmeltingService.quotaIncome(userEcologyHatchRecords.getUserId());
        return PageResult.success();
    }

    @PostMapping(value = "/adminDivideInto", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "熔炼后分成处理", notes = "熔炼后分成处理", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result AdminDivideInto(@Valid @RequestBody IdRequest request) {

        String key = RedisKeyEnum.ECOLOGY_HATCH_DIVIDE_INTO_TOPIC_LOCK.getKey() + request.getId();
        RLock lock = redisson.getLock(key);

        try {
            boolean res = lock.tryLock(3, TimeUnit.SECONDS);
            if (!res){
                throw new GlobalException("积分分成正在处理");
            }
            UserEcologyHatchRecords userEcologyHatchRecordsDaoById = userEcologyHatchRecordsDao.getById(request.getId());
            log.info("熔炼-分成处理 记录id:{},查询结果:{}", request.getId(),userEcologyHatchRecordsDaoById);
            ecologySmeltingService.newDivideInto(userEcologyHatchRecordsDaoById);
        } catch (Exception e) {
            WeChatUtil.sendLiGenWeChatMessage(StrUtil.format("熔炼-分成处理失败 记录id：{},异常:{}", request.getId(), e.getMessage()));
            log.error("熔炼-分成处理失败 记录id：{},异常:{}", request.getId(), e.getMessage());
        }finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return PageResult.success();
    }


    @PostMapping(value = "/initDaoEecologyPoints", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "初始化DAO生态燃料钱包", notes = "初始化DAO生态燃料钱包", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result initDaoEecologyPoints() {

        for (UserCreatorInfo userCreatorInfo : userCreatorInfoDao.getAllDaoList()) {
            DaoEcologyPoints daoEcologyPoints = new DaoEcologyPoints();
            daoEcologyPoints.setDaoId(userCreatorInfo.getId());
            daoEcologyPoints.setAmount(BigDecimal.ZERO);
            daoEcologyPoints.setFrozenAmount(BigDecimal.ZERO);
            daoEcologyPoints.insert();
        }
        return PageResult.success();
    }


    @ApiOperation(value = "熔炼后批量处理业绩", notes = "熔炼后批量处理业绩", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/batchSettlePerformance", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result batchSettlePerformance() throws Exception {
        List<UserEcologyHatchRecords> list = userEcologyHatchRecordsDao.getListByPlatformEffectiveAndDaoEffective();
        try {
            int count = 0;
            for (UserEcologyHatchRecords userEcologyHatchRecords : list) {
                ecologySmeltingService.settlePerformance(userEcologyHatchRecords);
                count++;
                log.info("熔炼后批量处理业绩 成功,当前处理第{}条,总计:{}", count, list.size());
            }

        } catch (Exception e) {
            log.error("熔炼后批量处理业绩 失败", e);
        }
        return Result.success();
    }

    @ApiOperation(value = "设置手机号", notes = "设置手机号", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/setPhone", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result<String> setPwd(@RequestBody @Valid IdRequest request) {
        UserInfo user = userInfoDao.getById(request.getId());
        if (BooleanUtil.isFalse(user.getSandAccountOpen())) {
            return Result.fail("您尚未完成开户");
        }

        if (BooleanUtil.isFalse(user.getSandFaceVerify())) {
            return Result.fail("您尚未完成人脸识别");
        }
        return Result.success(sandAccountHelper.setNewPhone(user));
    }

    @ApiOperation(value = "临时注册用户", notes = "临时注册用户", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/tmpInit", produces = MediaType.APPLICATION_JSON_VALUE)
     public Result<String> tmpInit(@RequestBody @Valid IdRequest request) {
        List<UserInfo> userInfos = userInfoDao.getNotInitUserList();
        for (UserInfo userInfo : userInfos) {
            userInfoService.initUserWalletAndAddr(userInfo);
        }
        return Result.success( );
    }

    @ApiOperation(value = "熔炼后批量处理业绩", notes = "熔炼后批量处理业绩", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/theRewardRecordToBeSettledIsInitialized", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result theRewardRecordToBeSettledIsInitialized(@RequestBody @Valid IdRequest request) throws Exception {
        log.info("熔炼后-周期预计奖励处理锁 记录id：{},处理开始",request.getId());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Assert.notNull(request.getId(),"熔炼后-周期预计奖励处理锁 记录id为空");

        RLock lock = redisson.getLock(RedisKeyEnum.PERIODIC_REWARD_INITIALIZATION.getKey()+ request.getId());

        try {
            boolean res = lock.tryLock(3, TimeUnit.SECONDS);
            if (!res){
                throw new GlobalException("该熔炼记录预计奖励在处理");
            }
            userPredictEcologyHatchRewardsRecordsService.save(request.getId());
        } catch (Exception e) {
            WeChatUtil.sendLiGenWeChatMessage(StrUtil.format("熔炼-周期预计奖励处理失败 记录id：{},异常:{}", request.getId(), e.getMessage()));
            log.error("熔炼-周期预计奖励处理失败 记录id：{},异常:{}", request.getId(), e.getMessage());
        }finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return Result.success( );
    }
}
